<?php 

class securepayment{

  /** 
   * $code determines the internal 'code' name used to designate "this" payment module
   * 
   * @var string
   */
  var $code;
   
  /**
   * $title is the displayed name for this payment method
   *
   * @var string
   */
  var $title;
  
  
  /**
   * $description is a soft name for this payment method
   *
   * @var string
   */
  var $description;
  
  
  /**
   * $enabled determines whether this module shows or not... in catalog.
   *
   * @var boolean
   */
  var $enabled;
  
    
  /**
   * other vars
   */ 
  var $npresponse;
  var $order_status;
   
 
  /**
   * @return securepayment object (class securepayment constructor)
   */
  function securepayment() {
    
    global $order; // global order object
  
    $this->code = 'securepayment'; //code of the module used with the fields name and other database entry purpose

    if (IS_ADMIN_FLAG === true) { //If view by admin
      $this->title = MODULE_PAYMENT_SECUREPAYMENT_TEXT_ADMIN_TITLE; // Payment module title in Admin
      
	  if (MODULE_PAYMENT_SECUREPAYMENT_STATUS == 'True' && (MODULE_PAYMENT_SECUREPAYMENT_MERCHANTID == 'Test' || MODULE_PAYMENT_SECUREPAYMENT_USERNAME == 'Test' || MODULE_PAYMENT_SECUREPAYMENT_PASSWORD == 'Test' || MODULE_PAYMENT_SECUREPAYMENT_ENCRYPTION_KEY == 'Test' || MODULE_PAYMENT_SECUREPAYMENT_ENCRYPTION_IV == 'Test')) {
	  	// If the securepayment module is installed but credentials is not configured then admin will show alert in red
        $this->title .=  '<span class="alert"> </span>';
      } elseif (MODULE_PAYMENT_SECUREPAYMENT_TESTMODE == 'Test') {
	    // If module is installed in testing mode then admin will show an alert
        $this->title .= '<span class="alert"> (in Testing mode)</span>';
      }
	  	  
    } else {
      $this->title = MODULE_PAYMENT_SECUREPAYMENT_TEXT_CATALOG_TITLE; // Payment module title in Catalog
    }
	
	// The description will initilise from language file (\includes\languages\english\modules\payment\securepayment.php)
    //$this->description = MODULE_PAYMENT_SECUREPAYMENT_TEXT_DESCRIPTION;
	
	// If module will work in front-end only if enabled (managed by admin)
    $this->enabled 	   = ((MODULE_PAYMENT_SECUREPAYMENT_STATUS == 'True') ? true : false);
	
	// Sort Order of securepayment in list (If more then one installed)
    $this->sort_order  = MODULE_PAYMENT_SECUREPAYMENT_SORT_ORDER;

    if ((int)MODULE_PAYMENT_SECUREPAYMENT_PREPARE_ORDER_STATUS_ID > 0) {
      $this->order_status = MODULE_PAYMENT_SECUREPAYMENT_PREPARE_ORDER_STATUS_ID;
    }

    if (is_object($order)) $this->update_status();

    /** Hosted form method action URL (default is on live website)
	 *  If admin set the securepayment module in Testing mode then action URL will on test server
	*/	
	$this->form_action_url = 'index.php?main_page=secpyt_redir_iframe';
	//$this->form_action_url = 'index.php?main_page=secpyt_redir_iframe&' . $this->send_data();
	//$this->form_action_url = 'https://www.hsdspay.com/Entrance';	
	
	//if (MODULE_PAYMENT_SECUREPAYMENT_TESTMODE == 'Test') $this->form_action_url = 'http://ecx.securepayment.com/Entrance';
	
  }


  /** securepayment
   * Calculate zone matches and flag settings to determine whether this module should display to customers or not
   */
   function update_status() {
    global $order, $db;

    if ( ($this->enabled == true) && ((int)MODULE_PAYMENT_SECUREPAYMENT_ZONE > 0) ) {
      $check_flag = false;
      $check = $db->Execute("select zone_id from " . TABLE_ZONES_TO_GEO_ZONES . " where geo_zone_id = '" . MODULE_PAYMENT_SECUREPAYMENT_ZONE . "' and zone_country_id = '" . $order->billing['country']['id'] . "' order by zone_id");
      while (!$check->EOF) {
        if ($check->fields['zone_id'] < 1) {
          $check_flag = true;
          break;
        } elseif ($check->fields['zone_id'] == $order->billing['zone_id']) {
          $check_flag = true;
          break;
        }
        $check->MoveNext();
      }

      if ($check_flag == false) {
        $this->enabled = false;
      }
    }
  }  
  
  /**
   * JS validation which does error-checking of data-entry if this module is selected for use
   * (Number, Owner Lengths)
   *
   * @return string
   */
   function javascript_validation() {
 	 return false;
  }  
  
  /**
   * Display Information Submission Fields on the Checkout Payment Page
   *
   * @return array
   */
   function selection() {   
  
      return array('id' => $this->code, 'module' => $this->title);    	
  }
  
  
  /**
   * Evaluates the Credit Card Type for acceptance and the validity of the Credit Card Number & Expiration Date
   * Not required in securepayment (Hosted Form Integration)
   */
   function pre_confirmation_check() {
  return false;
  }
  
  
  /**
   * Display Credit Card Information on the Checkout Confirmation Page
   * Not required in securepayment Hosted form integration 
   * @return array
   */
  function confirmation() {
  
     return array('title' => MODULE_PAYMENT_SECUREPAYMENT_TEXT_DESCRIPTION);
      //return false;
    }
	
function get_timezone_offset() {
  $origin_tz='America/New_York';  //中国时区 Asia/Shanghai
  $remote_tz=date_default_timezone_get();
    $origin_dtz = new DateTimeZone($origin_tz);
    $remote_dtz = new DateTimeZone($remote_tz);
    $origin_dt = new DateTime("now", $origin_dtz);
    $remote_dt = new DateTime("now", $remote_dtz);
    $offset = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);
    return $offset;
}


function create_order_number(){
  global $db;
  $time=time()+$this->get_timezone_offset();
  $order_prefix=ORDER_PREFIX.date('ymdH');
  $check=$db->Execute("SELECT orders_id FROM ".TABLE_ORDERS." WHERE orders_id like '".$order_prefix."%' ORDER BY  orders_id DESC LIMIT 1");
  $order_number= $check->fields['orders_id'] ? ORDER_PREFIX. str_replace(ORDER_PREFIX,'',$check->fields['orders_id'])+1 : $order_prefix.'01';
  return $order_number;
}
	
public function create_order()
    {
    	global $db, $order, $order_totals;
		
		$order_number=$this->create_order_number();
		
  	  // Code updated on dated: 06-03-2014 (will work for Backend Response Enabled)		
      //global $cartID, $cart_securepayment_ID,  $order, $order_totals, $db ,$currencies ;
 	  //$cart 	= $_SESSION['cart'];
	  //$cartID   = $cart->cartID;
	  
      $order->info['order_status'] = MODULE_PAYMENT_SECUREPAYMENT_ORDER_STATUS_ID;
        if ($order->info['total'] == 0) 
        {
            if (DEFAULT_ZERO_BALANCE_ORDERS_STATUS_ID == 0) 
            {
                $order->info['order_status'] = DEFAULT_ORDERS_STATUS_ID;
            } 
            else if ($_SESSION['payment'] != 'freecharger') 
            {
                $order->info['order_status'] = DEFAULT_ZERO_BALANCE_ORDERS_STATUS_ID;
            }
        }

        if ($_SESSION['shipping'] == 'free_free') 
        {
            $order->info['shipping_module_code'] = $_SESSION['shipping'];
        }
		  
		  // Entry in the Database Orders Table
          $sql_data_array = array( 
		                            'orders_id' => $order_number,
		                            'customers_id' => $_SESSION['customer_id'],
									'customers_name' => $order->customer['firstname'] . ' ' . $order->customer['lastname'],
									'customers_company' => $order->customer['company'],
									'customers_street_address' => $order->customer['street_address'],
									'customers_suburb' => $order->customer['suburb'],
									'customers_city' => $order->customer['city'],
									'customers_postcode' => $order->customer['postcode'],
									'customers_state' => $order->customer['state'],
									'customers_country' => $order->customer['country']['title'],
									'customers_telephone' => $order->customer['telephone'],
									'customers_email_address' => $order->customer['email_address'],
									'customers_address_format_id' => $order->customer['format_id'],
									'delivery_name' => $order->delivery['firstname'] . ' ' . $order->delivery['lastname'],
									'delivery_company' => $order->delivery['company'],
									'delivery_street_address' => $order->delivery['street_address'],
									'delivery_suburb' => $order->delivery['suburb'],
									'delivery_city' => $order->delivery['city'],
									'delivery_postcode' => $order->delivery['postcode'],
									'delivery_state' => $order->delivery['state'],
									'delivery_country' => $order->delivery['country']['title'],
									'delivery_address_format_id' => $order->delivery['format_id'],
									'billing_name' => $order->billing['firstname'] . ' ' . $order->billing['lastname'],
									'billing_company' => $order->billing['company'],
									'billing_street_address' => $order->billing['street_address'],
									'billing_suburb' => $order->billing['suburb'],
									'billing_city' => $order->billing['city'],
									'billing_postcode' => $order->billing['postcode'],
									'billing_state' => $order->billing['state'],
									'billing_country' => $order->billing['country']['title'],
									'billing_address_format_id' => $order->billing['format_id'],
									'payment_method' => MODULE_PAYMENT_SECUREPAYMENT_TEXT_CATALOG_TITLE,
									'payment_module_code' => $this->code,
									'shipping_method' => $order->info['shipping_method'],
									'shipping_module_code' => (strpos($order->info['shipping_module_code'], '_') > 0 ? substr($order->info['shipping_module_code'], 0, strpos($order->info['shipping_module_code'], '_')) : $order->info['shipping_module_code']),
									'coupon_code' => $order->info['coupon_code'],
									'cc_type' => $order->info['cc_type'],
									'cc_owner' => $order->info['cc_owner'],
									'cc_number' => $order->info['cc_number'],
									'cc_expires' => $order->info['cc_expires'],
									'date_purchased' => 'now()',
									'orders_status' => $this->order_status,
									'order_total' => $order->info['total'],
									'order_tax' => $order->info['tax'],
									'currency' => $order->info['currency'],
									'currency_value' => $order->info['currency_value'],
									'ip_address' => $_SESSION['customers_ip_address'] . ' - ' . $_SERVER['REMOTE_ADDR']
									);
 
          zen_db_perform(TABLE_ORDERS, $sql_data_array);
          $insert_id =$order_number;
		$order->notify('NOTIFY_ORDER_DURING_CREATE_ADDED_ORDER_HEADER', array_merge(array('orders_id' => $insert_id, 'shipping_weight' => $_SESSION['cart']->weight), $sql_data_array));
        
		for ($i = 0, $n = sizeof($order_totals); $i < $n; $i++) 
        {
            $sql_data_array = array('orders_id' => $insert_id,
                'title' => $order_totals[$i]['title'],
                'text' => $order_totals[$i]['text'],
                'value' => (is_numeric($order_totals[$i]['value'])) ? $order_totals[$i]['value'] : '0',
                'class' => $order_totals[$i]['code'],
                'sort_order' => $order_totals[$i]['sort_order']
            );
            zen_db_perform(TABLE_ORDERS_TOTAL, $sql_data_array);
            $order->notify('NOTIFY_ORDER_DURING_CREATE_ADDED_ORDERTOTAL_LINE_ITEM', $sql_data_array);
        } 

        $sql_data_array = array('orders_id' => $insert_id,
            'orders_status_id' => $this->order_status,
            'date_added' => 'now()',
            'customer_notified' => 0,
            'comments' => $order->info['comments']
        );
        zen_db_perform(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array);
        $order->notify('NOTIFY_ORDER_DURING_CREATE_ADDED_ORDER_COMMENT', $sql_data_array);
        
        //生成订单产品信息
        $order->create_add_products($insert_id);
      //$_SESSION['counter']=++$counter;
	  //$_SESSION['cart']->reset(true);
        return $insert_id;
  }
  
  /**
   * Build the data and actions to process when the "Submit" button is pressed on the order-confirmation screen.
   * This sends the data to the payment gateway for processing (Hidden form creation step).
   * (These are hidden fields on the checkout confirmation page)
   *
   * @return string
   */
  function process_button() {
  //echo $this->order_status; exit;
	global $order,$db,$sendto, $currency, $cart_securepayment_ID,$shipping, $woocommerce,$v_oid;
		 
		  
	 $query = $db->Execute("select orders_status_id from " . DB_PREFIX . "orders_status where orders_status_name='SecurePayment[Unpaid]' and language_id={$_SESSION['languages_id']} limit 1");
        if(!$query->RecordCount())
        {
            die('Wrong order status: ' . $status);
        }
        $status_id = $query->fields['orders_status_id'];

	 $array = $db->Execute("select * from " . TABLE_ORDERS . " where orders_status='".$status_id."' and payment_module_code = 'securepayment' and
	customers_email_address = '".$order->customer['email_address']."' and currency = '".$order->info['currency']."' and order_total = '".$order->info['total']."' order by orders_id desc limit 0, 1");
	if ( $array->fields['orders_id'])
	{
		$_SESSION['orders_id']=$array->fields['orders_id'];	// 订单编号
	}else{
		$_SESSION['orders_id']= $this->create_order();	// 订单编号
	}
	
    return false;
	
  }
  
  
  /**
   * Handle the order after the securepayment Hosted Form Payment processed
   * Show error message if the payment is not done successfully else the order will get inserted in the database
  
   * @return 
   */
   function before_process() {	    
  	return false;
  }
  
  
  /**
   * Post-processing activities
   *
   * @return boolean
   */
   function after_process() {
    return false;	
  }
  
  /**
   * Post-processing activities (error-handling)
   *
   * @return boolean
   */  
   function output_error() {
    return false;
  }  
  
  /**
   * Check to see whether module is installed
   *
   * @return boolean
   */
   function check() {
    global $db;
    if (!isset($this->_check)) {
      $check_query = $db->Execute("select configuration_value from " . TABLE_CONFIGURATION . " where configuration_key = 'MODULE_PAYMENT_SECUREPAYMENT_STATUS'");
      $this->_check = $check_query->RecordCount();
    }
    return $this->_check;
  }
  
   
  /**
   * Install the SECUREPAYMENT payment module and its configuration settings (database configuration queries)
   *
   * @return
   */
  function install() {
    
	global $db, $messageStack;
    
	if (defined('MODULE_PAYMENT_SECUREPAYMENT_STATUS')) { // return a message if the module is already found installed
      $messageStack->add_session('SecurePayment module already installed.', 'error');
      zen_redirect(zen_href_link(FILENAME_MODULES, 'set=payment&module=SECUREPAYMENT', 'NONSSL'));
      return 'failed';
    }
	
     $check_query = $db->Execute("select orders_status_id from " . TABLE_ORDERS_STATUS . " where orders_status_name = 'SecurePayment[Unpaid]' limit 1");
     if ($check_query->RecordCount() < 1) {
	 
        $status_query = $db->Execute("select max(orders_status_id) as status_id from " . TABLE_ORDERS_STATUS);         		
        $status_id    = $status_query->fields['status_id'] + 1;
        $languages    = zen_get_languages();

        foreach ($languages as $lang) {
          $db->Execute("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('" . $status_id . "', '" . $lang['id'] . "', 'SecurePayment[Unpaid]')");
        }

        $flags_query = $db->Execute("describe " . TABLE_ORDERS_STATUS . " public_flag");
        if ($flags_query->RecordCount() ==1) {
          $db->Execute("update " . TABLE_ORDERS_STATUS . " set public_flag = 0 and downloads_flag = 0 where orders_status_id = '" . $status_id . "'");
        }
      } else {
        $status_id = $check_query->fields['orders_status_id'];
      }	
	
	
	// Database configuration setting will done during installation of SECUREPAYMENT Payment Module
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('开/关Secure Payment支付', 'MODULE_PAYMENT_SECUREPAYMENT_STATUS', 'True', '您想开Secure Payment支付吗', '6', '0', 'zen_cfg_select_option(array(\'True\', \'False\'), ', now())");
	
	$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('您的商户号', 'MODULE_PAYMENT_SECUREPAYMENT_MERCHANTID', '', '', '6', '0', now())");
			
	$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('您的商户后台密钥', 'MODULE_PAYMENT_SECUREPAYMENT_ENCRYPTION_KEY', '', '登陆商户后台 ,获取密钥请查看安装包内的说明文档', '6', '0', now())");
	
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, date_added) values ('Transaction Mode', 'MODULE_PAYMENT_SECUREPAYMENT_TESTMODE', 'Production', 'Transaction mode used for processing orders', '6', '0', 'zen_cfg_select_option(array(\'Test\', \'Production\'), ', now())");
	    
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('在网站前台支付排序', 'MODULE_PAYMENT_SECUREPAYMENT_SORT_ORDER', '1', '', '6', '0', now())");
	
	$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Page Style', 'MODULE_PAYMENT_SECUREPAYMENT_PAGE_STYLE', '5', '设置支付页面的样式,[1-5]分别代表5种不同样式大小，数字越大宽度越大', '6', '0', now())");
	
	$db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Language', 'MODULE_PAYMENT_SECUREPAYMENT_LANGUAGE', 'EN', '支付界面的语言：EN(英语),FR(法语),DE(德语),IT(意大利语),RU(俄语),JP(日语),ZH(中文)]', '6', '0', now())");
	
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('支付失败订单状态', 'MODULE_PAYMENT_SECUREPAYMENT_PREPARE_ORDER_STATUS_ID', '" . $status_id . "', '', '6', '0', 'zen_cfg_pull_down_order_statuses(', 'zen_get_order_status_name', now())");	
	 
	/** Add a new payment status in Zen_Cart orders_status table named as SECUREPAYMENT[Payment Received]
	*   If this status name is already exists then the id of that status will be used for default selection of order during installation
	*   Else the newly created id will used for the same
	*/  	
	$fetch_sql = "select * from " . TABLE_ORDERS_STATUS . " where orders_status_name = 'SecurePayment[Payment Received]'";
	$result = $db->Execute($fetch_sql);
	if ($result->RecordCount() > 0) {
    	$default_status_id = $result->fields['orders_status_id'];
	}else{
		$result  = $db->Execute("select max(orders_status_id) as max_status_id  from " . TABLE_ORDERS_STATUS);		
	    $inserted= $db->Execute("insert into " . TABLE_ORDERS_STATUS . " (orders_status_id, language_id, orders_status_name) values ('".($result->fields['max_status_id']+1)."','".$_SESSION['languages_id']."', 'SecurePayment[Payment Received]')");
		if($inserted)  $default_status_id = ($result->fields['max_status_id']+1);
	}	

	// Alter the table payment_method field for strong the method name with image icon
    $db->Execute("ALTER TABLE `".DB_PREFIX."orders` CHANGE `payment_method` `payment_method` VARCHAR( 255 ) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT ''");
	
    $db->Execute("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, set_function, use_function, date_added) values ('支付成功订单状态', 'MODULE_PAYMENT_SECUREPAYMENT_ORDER_STATUS_ID', '".$default_status_id."', '', '6', '0', 'zen_cfg_pull_down_order_statuses(', 'zen_get_order_status_name', now())");
	
	/* New Table created if not found named as "SECUREPAYMENT" 
	 * The table is used for storing all the transactions (that has been done by SECUREPAYMENT)	
	 * The table data can be used further payment realted pages/matters (It's always better to store the response of payment gateway)
	*/
	$db->Execute("CREATE TABLE IF NOT EXISTS `".DB_PREFIX."SECUREPAYMENT` (`id` int(11) unsigned NOT NULL AUTO_INCREMENT,`customer_id` int(11) NOT NULL DEFAULT '0',
`order_id` int(11) NOT NULL DEFAULT '0',`result` varchar(100) DEFAULT NULL,`merchant_id` varchar(15) DEFAULT NULL,`operation_type` varchar(10) DEFAULT NULL,`operation_mode` varchar(10) DEFAULT NULL,`order_reference` varchar(255) DEFAULT NULL,`transaction_id` varchar(20) DEFAULT NULL,`currency` varchar(5) DEFAULT NULL,`amount` varchar(10) DEFAULT NULL,`description` varchar(255) DEFAULT NULL,`SECUREPAYMENT_order_id` varchar(100) DEFAULT NULL,`reference` varchar(100) DEFAULT NULL,`code` varchar(20) DEFAULT NULL,`explanation` varchar(255) DEFAULT NULL,`validation_type` varchar(20) DEFAULT NULL,`cause` varchar(100) DEFAULT NULL,`response_code` text,`time` varchar(50) NOT NULL DEFAULT '',`session_id` varchar(255) NOT NULL DEFAULT '',PRIMARY KEY (`id`)	) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;");
  
  }
  
  
  /**
   * Remove the module and all its configuration settings from database SECUREPAYMENT
   *
   */
   function remove() {
    global $db;
    $db->Execute("delete from " . TABLE_CONFIGURATION . " where configuration_key LIKE 'MODULE\_PAYMENT\_SECUREPAYMENT\_%'");
    echo'SecurePayment WAS UNSTALLED SUCCESSFULLY';
  }
  
  
  /**
   * Internal list of configuration keys used for configuration of the SECUREPAYMENT modulfe 
   * @return array
   */
   function keys() {
    return array(
		'MODULE_PAYMENT_SECUREPAYMENT_STATUS',		
		'MODULE_PAYMENT_SECUREPAYMENT_TESTMODE',
		'MODULE_PAYMENT_SECUREPAYMENT_MERCHANTID',
		'MODULE_PAYMENT_SECUREPAYMENT_ENCRYPTION_KEY',		 		 		 				 
		'MODULE_PAYMENT_SECUREPAYMENT_PREPARE_ORDER_STATUS_ID',
		'MODULE_PAYMENT_SECUREPAYMENT_ORDER_STATUS_ID', 
		'MODULE_PAYMENT_SECUREPAYMENT_PAGE_STYLE',
		'MODULE_PAYMENT_SECUREPAYMENT_LANGUAGE',
		'MODULE_PAYMENT_SECUREPAYMENT_SORT_ORDER' 		 		 
	);
	
  }
} 